import styles from './ballCard.module.scss';
import { GiBasketballJersey } from 'react-icons/gi';
import { IPropsBall } from './ballCard.types';
import Button from '../button/button';
import { useAppDispatch, useAppSelector } from '../../store/hooks';
import { addBallToCart, deleteBallOnCart } from '../../store/cart/cart.slice';
import {fetchAddFavoritesBallSlice} from '../../store/favorites/favorites.actions';
import { Modal } from '../modalWindows/modalWindows';
import {  useState } from 'react';
import { BallCartMore } from '../ballCartMore/ballCartMore';


export const BallCard = ({ ball }: IPropsBall) => {
	const dispatch = useAppDispatch();
	const { favoritesBalls } = useAppSelector((state) => state.addFavoriteBall);
	const { token } = useAppSelector((state) => state.authorization.user);
	const { balls } = useAppSelector((state) => state.cart);
	const [test, setTest] = useState(false);
	const addBallOnCart = (e: React.MouseEvent<HTMLButtonElement>) => {
		e.stopPropagation();
		{
			hasOnCart === true
				? dispatch(deleteBallOnCart(ball.id))
				: dispatch(addBallToCart(ball));
		}
	};
	const hasOnCart = balls.some((item) => item.id === ball.id);

	const hasOnFavorites =
    Array.isArray(favoritesBalls) &&
    favoritesBalls.some((item) => item.name === ball.name);
	
	const handleImageClick = () => {
		setTest(true);
	};
	
	const handleCloseModal = () => {
		setTest(false);
	};
	
	const fetchAddItemBallOnFavorite = () => {
		dispatch(fetchAddFavoritesBallSlice(ball));
	};

	const toggleFavoriteBall = (e: React.MouseEvent<HTMLSpanElement>) => {
		e.stopPropagation();
		hasOnFavorites !== true
			? fetchAddItemBallOnFavorite()
			: alert('Товар уже в избранном');
	};
	return (
		<div className={styles.ball_cart}>
			{
				token &&  
			<span onClick={toggleFavoriteBall} className={styles.form}>
				<GiBasketballJersey
					color={hasOnFavorites ? '#ff0000' : '#ffa500'}
					size={40}
				/>
			</span>
			}
			<div>
				<div className={styles.img}>
					<img
						style={{ cursor: 'pointer' }}
						onClick={handleImageClick}
						src={ball.image}
						width={300}
					/>
				</div>
				<div className={styles.price}>
					<p>Цена {ball.price} р</p>
					<Button
						deleted={hasOnCart ? true : false}
						disabled={token !== null ? false : true}
						onClick={addBallOnCart}
						appearance="small"
					>
						{hasOnCart !== true ? 'В корзину' : 'Удалить'}
					</Button>
				</div>
				<div className={styles.description}>
					<p className={styles.item}>Описание:</p>
					<p>{ball.title}</p>
				</div>
				{test && <Modal onClose={handleCloseModal}><BallCartMore ball={ball} /></Modal>}
			</div>
		</div>
	);
};
